<template>
  <div>
    <a-card :tab-list="tabList" :active-tab-key="currentTab" @tabChange="changeTab">
      <a-row gutter="24">
        <a-col :span="4" :md="4" :xl="4">
          <a-form-model-item >
            <a-range-picker v-model="searchForm.dateRange" @change="changeDate" style="width: 100%;" :ranges="ranges"/>
          </a-form-model-item>
        </a-col>
        <a-col :span="6" :md="6" :xl="6" >
              <a-form-model-item prop="search">
                <a-input v-model="searchForm.search" allowClear placeholder="产品编号/采购单号/规格/产品名称/供应商名称" style="padding-left: 0px; padding-right: 0px;width: 100%; margin-right: 0px;" />
                <!-- <a-input v-model="searchForm.search" allowClear :placeholder="NewdateToString" /> -->
              </a-form-model-item>
        </a-col>
        <a-col :span="4" :md="4" :xl="4"  style="width: 280px;margin-left: 10px;">
            <a-form-model-item >
              <a-button-group> 
                <a-button type="primary" :loading="loading" @click="search"><a-icon type="search" />查询</a-button>    
                <a-button :loading="downloadLoading" @click="handleDownload"><a-icon type="file-excel" />导出</a-button>    
              </a-button-group>
            </a-form-model-item>
        </a-col>
      </a-row>

      <a-descriptions :column="{ xxl: 4, xl: 4, lg: 4, md: 2, sm: 2, xs: 1 }" style="text-align: center;">
        <a-descriptions-item label="采购次数"><span class="total">{{totalCount}}</span></a-descriptions-item>
        <a-descriptions-item label="采购总数量"><span class="total">{{totalQuantity}}</span></a-descriptions-item>
        <a-descriptions-item label="采购总金额"><span class="total">{{totalAmount}}</span></a-descriptions-item>
      </a-descriptions>

      <div>
        <flow-pane v-show="currentTab === 'flow'" :items="items" :loading="loading" :pagination="pagination" @tableChange="tableChange" />
        <goods-pane v-show="currentTab === 'goods'" :items="items" :loading="loading" :pagination="pagination" @tableChange="tableChange" />
      </div>
      <div style="text-align: center; margin-top: 12px;">
        <a-spin :spinning="loading && searchForm.page > 1" />
      </div>
    </a-card>
  </div>
</template>

<script>
  import { purchaseReportStatistics, purchaseReportDetialsList, purchaseReportByGoodsList } from '@/api/report'
  import { goodsClassificationOption } from '@/api/option'
  import { List} from '@/api/common'
  import { datetimeToString} from "@/utils/common";
  import NP from 'number-precision'
  import moment from 'moment'

  export default {
    name: 'SalesReport',
    components: {
      FlowPane: () => import('./flowPane'),
      GoodsPane: () => import('./goodsPane'),
    },
    data() {
      return {
        downloadLoading: false,
        downloadList: [],
        ranges: {
        '今日': [moment().startOf('day'), moment().startOf('day')],
        '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        '本周': [moment().week(moment().week()).startOf('week'), moment().week(moment().week()).endOf('week')],
        '上周': [moment().subtract(1,'week').startOf('week'), moment().subtract(1,'week').endOf('week')],
        '本月': [moment().startOf('month'), moment().startOf('day')],
        '上月': [moment().subtract(1,'month').startOf('month'), moment().subtract(1,'month').endOf('month')],
       },
        NP,
        currentTab: 'flow',
        radioValue: '0',
        tabList: [
          {
            key: 'flow',
            tab: '采购明细',
          },
          // {
          //   key: 'goods',
          //   tab: '按产品汇总',
          // },
        ],
        searchForm: {
          dateRange: [moment().startOf('day'), moment().startOf('day')],
          category: null,
          page: 1,
          page_size: 15,
          search:null
        },
        loading: true,
        categoryItems: [],
        total: {
          quantity: 0,
          cost: 0,
          amount: 0,
        },
        items: [],
        pagination: { current: 1, total: 0, pageSize: 15 },
      };
    },
    computed: {
      totalCount() {
        return this.total.total_count ? this.total.total_count : 0
      },
      totalQuantity() {
        return this.total.total_quantity ? NP.round(this.total.total_quantity, 2) : 0
      },
      totalAmount() {
        return this.total.total_amount ? NP.round(this.total.total_amount, 2) : 0
      },
    },
    methods: {
      getNewdownloadList(downloadList) {
          let o={
              index:'合计',
              purchase_quantity:0,
              total_amount:0,
          }

          if (downloadList) {
              let i=0
              downloadList.forEach(e => {
                  i+=1
                  e['index'] = i
                  e.total_amount = NP.round(e.total_amount,2)
                  o.purchase_quantity+=parseFloat(e.purchase_quantity)
                  o.total_amount+=parseFloat(e.total_amount)
              });
              downloadList.push(o)
          } else {
            downloadList = []
          }
      },
      handleDownload() {
        this.loading = true;
        this.downloadLoading = true;
        let form = {
          start_date: this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[0].format('YYYY-MM-DD') : null,
          end_date: this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[1].format('YYYY-MM-DD') : null,
          category: this.searchForm.category,
          page: this.searchForm.page,
          page_size: 99999,
          search: this.searchForm.search,
        };
        if (form.end_date) {
          form.end_date = moment(form.end_date).add(1, 'days').format('YYYY-MM-DD');
        }
          List(form,'purchase_reports/detials').then(response  => {
          const resp = response.data;        
          this.downloadList = response.results;
          this.getNewdownloadList(this.downloadList) 
          // this.downloadList.forEach(e => {
          //     e.jgry_items=this.jgry_items2names(e.jgry_items)
          //     e.is_void=e.is_void?'已作废':"正常"
          // });
          // console.log('this.downloadList:',this.downloadList )
          this.searchForm.page_size=15
          import("@/vendor/Export2ExcelNew").then(excel => {
            const tHeader1 = [
              "序号",
              "产品编号",
              "产品名称",
              "规格",
              "分类名称",
              "单位",
              "采购单价",
              "采购数量",   
              "总金额(元)",
              "采购单号",
              "仓库",
              "供应商",              
              "经手人",
              "创建时间",
            ];
            const filterVal = [
              "index",
              "goods_number",
              "goods_name",
              "goods_spec",
              "category_name",
              "unit_name",
              "purchase_price",
              "purchase_quantity",
              "total_amount",
              "purchase_order_number",
              "warehouse_name",
              "supplier_name",
              "handler_name",
              "create_time",
            ];
            //const filterVal = tHeader;
            //不要将下载数据与显示数据列表用同一个变量，否则要出问题
            const list = this.downloadList;
            let downloadList = list;
  
            const data = this.formatJson(filterVal, downloadList);
            console.log('data:',data)
            const title = ["采购明细"+datetimeToString(new Date())];
            const sheetname = "采购明细";
            const merges = [ "A1:P1"];
            excel.export_json_to_excel({
              title,
              header: tHeader1,
              // multiHeader:[tHeader1],            
              data,
              filename: "采购明细"+datetimeToString(new Date()),
              merges,
              // autoWidth: this.autoWidth,
              autoWidth: this.autoWidth,
              bookType: this.bookType,
              sheetname
            });
            this.loading = false;
            this.downloadLoading = false;
          });
        });
      },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    },
      initailize() {
        if (this.$route.query.type) {
          this.currentTab = this.$route.query.type;
        } else {
          this.$router.replace({ query: { type: this.currentTab } })
        }
        this.list();
        goodsClassificationOption({ page_size: 99999 }).then(resp => {
          this.categoryItems = resp.results;
        });
      },
      list() {
        let form = {
          start_date: this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[0].format('YYYY-MM-DD') : null,
          end_date: this.searchForm.dateRange.length > 0 ? this.searchForm.dateRange[1].format('YYYY-MM-DD') : null,
          category: this.searchForm.category,
          page: this.searchForm.page,
          page_size: this.searchForm.page_size,
          search: this.searchForm.search,
        };

        if (form.end_date) {
          form.end_date = moment(form.end_date).add(1, 'days').format('YYYY-MM-DD');
        }

        this.loading = true;
        purchaseReportStatistics(form).then(resp => {
          this.total = resp;
        })
        if (this.currentTab === 'flow') {
          purchaseReportDetialsList(form).then(resp => {
            this.items = resp.results;
            this.pagination.total = resp.count;
          }).finally(() => {
            this.loading = false;
          });
        } else {
          purchaseReportByGoodsList(form).then(resp => {
            this.items = resp.results;
            this.pagination.total = resp.count;
          }).finally(() => {
            this.loading = false;
          });
        }
      },
      tableChange(pagination, filters, sorter) {
        this.searchForm.page = pagination.current;
        this.pagination.current = pagination.current;
        this.searchForm.ordering = `${sorter.order == 'descend' ? '-' : ''}${sorter.field}`;
        this.list();
      },
      search() {
        this.searchForm.page = 1;
        this.pagination.current = 1;
        this.list();
      },
      changeTab(key) {
        this.currentTab = key;
        this.$router.replace({ query: { type: this.currentTab } })
        this.resetForm();
        this.search();
      },
      changeRadio(evt) {
        let value = evt.target.value;
        if (value < 0) {
          this.searchForm.dateRange = [moment().startOf('day').add(value, 'day'), moment().startOf('day')]
        } else {
          this.searchForm.dateRange = [moment().startOf('day').subtract(value, 'day'), moment().startOf('day').subtract(value, 'day'),]
        }
        this.search();
      },
      changeDate() {
        this.radioValue = null;
        this.search();
      },
      changeCategory() {
        this.search();
      },
      resetForm() {
        this.radioValue = '0';
        this.searchForm = {
          dateRange: [moment().startOf('day'), moment().startOf('day')],
          category: null,
          page: 1,
          page_size: 15
        };
      },
    },
    mounted() {
      this.initailize();
    },
  }
</script>

<style scoped>
  .total {
    color: #a94442;
  }
</style>